<script setup>
import {User,Lock,Cellphone,Right,Back} from '@element-plus/icons-vue'
import {ref,watch} from 'vue'
import {loginService,registerService,resPasswordService,emailCodeService} from '@/api/LoginManager'
import { useUserStore } from '@/stores/user';
import router from '@/router';

const pageType = ref(0)
const userStore = useUserStore()

const formModel = ref({
      userName:'',
      phoneNumber:'',
      password:'',
      rePassword:'',
      emailNum:'',
})

const formRef = ref()

const rules = {
    username:[{required:true,message:'请输入用户名',trigger:'blur'}],
    phoneNumber:[
        {required:true,message:'请输入手机号',trigger:'blur'},
        {min:11,max:11,message:'请检查您的手机号',trigger:'blur'},
    ],
    password:[
        {required:true,message:'请输入密码',trigger:'blur'},
        {min:8,message:'密码最小为8位',trigger:'blur'}
    ],
    rePassword:[
        {required:true,message:'请输入密码',trigger:'blur'},
        {min:8,message:'密码最小为8位',trigger:'blur'},
        {
            validator: (rule,value,callback) => {
                if(value === formModel.value.password){
                    return callback()
                }else{
                    return callback(new Error("密码不一致"))
                }
           }
        }
    ]
}

const registerBtn = async () => {
    await formRef.value.validate()
    await registerService(formModel.value)
    ElMessage.success('注册成功！')
    pageType.value = 0
}

const loginBtn = async () => {
    await formRef.value.validate()
    const res = await loginService(formModel.value);
    userStore.setId(res.data.data.id)
    userStore.setUserName(res.data.data.userName);
    userStore.setUserType(res.data.data.userType);
    userStore.setToken(res.data.data.id)
    console.log(userStore.user)
    ElMessage.success('登录成功！')
    if(res.data.data.userType === '1'){
        router.push('/main/task')
    }else{
        router.push('/')
    }
}

const countdown = ref(10);
const second = ref(10)
let timer=null
const refCodeBtn = ref(null)
const startCountdown = () => {
      if (timer) return; // 防止重复启动定时器
      timer = setInterval(() => {
        second.value--;
        if (second.value === 0) {
          clearInterval(timer);
          timer = null;
          second.value = countdown.value
        }
      }, 1000);
    };
const getTelCode = async () => {
    if(!formModel.value.emailNum){
        ElMessage.error("请填写您的邮箱")
        return
    }
    const res = await emailCodeService(formModel.value);
    ElMessage.success(res.data.data)
    startCountdown();
}

const resetPassword = async () => {
    const res = await resPasswordService(formModel.value)
    ElMessage.success(res.data.message)
    pageType.value = 0
}

watch(pageType,()=>{
    formModel.value = {
        username:'',
        password:'',
        phoneNumber:'',
        rePassword:'',
        emailNum:''
    }
})
</script>

<template>
    <el-row class="login-page">
        <el-col :span="9" :offset="3" class="bg">  
            <H1>Sign in to </H1>
            <h1>Select Your Course</h1>
            <div class="cus-bg">

            </div>
        </el-col>
        <el-col :span="6" :offset="3" class="form">
            
            <el-form 
            :model="formModel" 
            :rules="rules" 
            ref="formRef"

            size=large v-if="pageType === 2"> 
                <el-form-item>
                    <h1>注册</h1>
                </el-form-item>
                <el-form-item prop="userName">
                    <el-input
                    v-model="formModel.userName" 
                    :prefix-icon="User" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item prop="phoneNumber">
                    <el-input 
                    v-model="formModel.phoneNumber"
                    :prefix-icon="Cellphone" placeholder="请输入手机号"></el-input>
                </el-form-item>
                <el-form-item prop="emailNum">
                    <el-input 
                    v-model="formModel.emailNum"
                    :prefix-icon="Cellphone" placeholder="请输入邮箱"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input
                    v-model="formModel.password"
                    :prefix-icon="Lock" type="password" placeholder="请输入密码"></el-input>
                </el-form-item>
                <el-form-item prop="rePassword">
                    <el-input 
                    v-model="formModel.rePassword"
                    :prefix-icon="Lock" type="password" placeholder="请重新输入密码"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button @click="registerBtn" class="loginBtn" type="primary">注册</el-button>
                </el-form-item>
                <el-form-item>
                    <el-link :underline="false" @click="pageType = 0"> <el-icon><Back /></el-icon> 返回 </el-link>
                </el-form-item>
            </el-form>

            <el-form 
            :model="formModel" 
            :rules="rules" 
            ref="formRef"
            size=large v-if=" pageType === 0"> 
                <el-form-item>
                    <el-link @click="pageType = 0" :underline="false"><h2>账号登录</h2></el-link>
                </el-form-item>
                <el-form-item prop="phoneNumber">
                    <el-input
                    v-model="formModel.phoneNumber" 
                    :prefix-icon="User" placeholder="请输入手机号"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input 
                    v-model="formModel.password" 
                    :prefix-icon="Lock" type="password" placeholder="请输入密码"></el-input>
                </el-form-item>
                <el-form-item class="flex">
                    <div class="flex">
                        <el-checkbox>记住我</el-checkbox>
                        <el-link type="primary" @click="pageType = 1" :underline="false">忘记密码？</el-link>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button @click="loginBtn" class="loginBtn" type="primary">登录</el-button>
                </el-form-item>
                <el-form-item>
                    <el-link :underline="false" @click="pageType = 2">去注册 <el-icon><Right /></el-icon> </el-link>
                </el-form-item>
            </el-form>

            <el-form 
            :model="formModel" 
            :rules="rules" 
            ref="formRef"
            size=large v-if="pageType === 1"> 
                <el-form-item>
                    <el-link type = "info" @click="pageType = 0" :underline="false"><h2>账号登录</h2></el-link>
                    <el-divider direction="vertical"></el-divider>
                    <el-link @click="pageType = 1" :underline="false"><h2>重置密码</h2></el-link>
                </el-form-item>
                <el-form-item prop="emailNum">
                    <el-input
                    v-model="formModel.emailNum" 
                    :prefix-icon="User" placeholder="请输入邮箱号码"></el-input>
                </el-form-item>
                <el-form-item prop="emailCode">
                    <el-input 
                        v-model="formModel.emailCode" 
                        :prefix-icon="Lock" type="text" placeholder="请输入验证码">
                        <template #append>
                        <el-button ref="refCodeBtn" @click="getTelCode">{{ second === countdown ? '获取验证码': second + 's后重新获取' }}</el-button>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="emailNum">
                    <el-input
                    v-model="formModel.password" 
                    :prefix-icon="User" placeholder="请输入新密码"></el-input>
                </el-form-item>
                <el-form-item class="flex">
                    <div class="flex">
                        <el-checkbox>记住我</el-checkbox>
                        <el-link type="primary" :underline="false">忘记密码？</el-link>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button @click="resetPassword" class="loginBtn" type="primary">重置密码</el-button>
                </el-form-item>
                <el-form-item>
                    <el-link :underline="false" @click="pageType = 2">去注册 <el-icon><Right /></el-icon> </el-link>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>

</template>

<style scoped>
    .login-page{
        height: 100vh;
        background-color: #fff;
    }

    .bg{
        display: flex;
        flex-direction: column;
        justify-content: center;
        position: relative;
    }
    .bg h1{
        font-size: 3em;
        font-weight: 700;
        color: black;
    }

    .cus-bg {
        display: flex;
        width: 300px;
        height: 200px;
        background: linear-gradient(to right,#4460f1,#c471ed,#f64f59);
        filter: blur(110px);
        position: absolute;
    }

    .form{
        display: flex;
        flex-direction: column;
        justify-content: center;
        user-select: none;
    }

    .flex {
        width: 100%;
        display: flex;
        justify-content: space-between;
    }

    .loginBtn {
        flex: 1;
    }
    
</style>
